package com.avic.rong.fragment.collect;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.R;
import com.avic.rong.activity.mine.CollectionActivity;
import com.avic.rong.adapter.collect.StandardAdapter;
import com.avic.rong.api.collect.DeleteCollectApi;
import com.avic.rong.api.collect.StandardCollectApi;
import com.avic.rong.bean.collect.StandardCollectBean;
import com.avic.rong.fragment.BaseLazyFragment;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class  StandardFragment extends BaseLazyFragment implements OnRefreshLoadMoreListener{


    @BindView(R.id.recv_standard)
    RecyclerView recv_standard;
    @BindView(R.id.srl_standard)
    SmartRefreshLayout srl_standard;
    @BindView(R.id.tv_wushujv)
    TextView tvwuShujv;

    private View view;
    private Unbinder unbinder;
    private String login_token;

    private int limit = 10;
    private int offset = 1;
    private StandardAdapter standardAdapter;
    private int newOffset;
    private boolean isRefresh;
    private StandardCollectApi standardCollectApi;
    private LoadingLayout loading_layout;

    public StandardFragment() {
        // Required empty public constructor
    }
    //测试用的


    private int mPosition;

    private String title;
    private Context mContext;

    private ArrayList<StandardCollectBean> mList;

    public static StandardFragment getInstance(String title, Context mContext) {
        StandardFragment standardFragment = new StandardFragment();
        standardFragment.title = title;
        standardFragment.mContext = mContext;
        return standardFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.e("StandardFragment", "onAttach: ");
        if (SharedPreferencesUtil.isLogin()) {
            login_token = SharedPreferencesUtil.getLoginToken();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_standard, container, false);

        Log.e("StandardFragment", "onCreateView: ");
        unbinder = ButterKnife.bind(this, inflate);

        loading_layout = inflate.findViewById(R.id.loading_layout);
        loading_layout.setStatus(LoadingLayout.LOADING);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());

        recv_standard.setLayoutManager(linearLayoutManager);

        mList = new ArrayList<>();
        standardAdapter = new StandardAdapter(getContext(), mList);
        recv_standard.setAdapter(standardAdapter);

        loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                HttpManager.getInstance().doHttpDeal(standardCollectApi);
                loading_layout.setStatus(LoadingLayout.LOADING);
            }

            @Override
            public void onReturn(View v) {
                getActivity().onBackPressed();
            }
        });


        standardAdapter.setStandButtonClick(new StandardAdapter.StandButtonClick() {
            @Override
            public void onClick(StandardCollectBean bean, int position) {
                mPosition = position;
                DeleteCollectApi deleteCollectApi = new DeleteCollectApi((CollectionActivity) mContext, deleteCollectListener);
                deleteCollectApi.setArgument(login_token, 6, bean.getTargetId());
                HttpManager.getInstance().doHttpDeal(deleteCollectApi);
            }
        });

        srl_standard.setOnRefreshLoadMoreListener(this);

        return inflate;

    }

    HttpOnNextListener<BaseResultEntity> deleteCollectListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                mList.remove(mPosition);
                ToastTools.showPublicToast("取消收藏成功");
                standardAdapter.notifyDataSetChanged();
            } else {
                ToastTools.showPublicToast(baseResultEntity.getMsg());
            }
        }
    };

    private void initData() {
        standardCollectApi = new StandardCollectApi((CollectionActivity) getActivity(), standardCollectListener);
        standardCollectApi.setArgument(login_token, offset, limit);
//        standardCollectApi.setCancel(false);
//        standardCollectApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(standardCollectApi);
    }

    HttpOnNextListener<BaseResultEntity> standardCollectListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                List<StandardCollectBean> data = (List<StandardCollectBean>) baseResultEntity.getData();
                Log.e("StandardFragment", "onNext: " + data.toString());
                if (data != null) {

                    if (isRefresh){
                        mList.clear();
                    }

                    loading_layout.setStatus(LoadingLayout.SUCCESS);

                    mList.addAll(data);
                    if (standardAdapter!=null) {
                        standardAdapter.notifyDataSetChanged();
                    }
                    if (mList!=null&&mList.size()<=0){
                                loading_layout.setStatus(LoadingLayout.EMPTY);
                                loading_layout.setEmptyImageVisible(true);
                                loading_layout.setEmptyText("您还未添加过收藏哦~");
                                loading_layout.setEmptyImage(R.mipmap.collection_mpty);
                    }
                    if (srl_standard!=null) {
                        if (isRefresh) {
                            srl_standard.finishRefresh();
                        } else {
                            srl_standard.finishLoadMore();
                        }
                    }
                }
            }else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        isRefresh = false;
        offset = offset + 1;
        standardCollectApi.setOffset(offset);
        HttpManager.getInstance().doHttpDeal(standardCollectApi);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isRefresh = true;
        offset = 1;
        standardCollectApi.setOffset(offset);
        HttpManager.getInstance().doHttpDeal(standardCollectApi);
    }

    @Override
    public void loadData() {
        //获取数据
        initData();
    }
}
